<template>
    <div>
      <el-form :inline="true" :model="queryForm" class="demo-form-inline">
        <el-form-item label="京剧展示内容管理">
          <el-input v-model="queryForm.kw" placeholder="标题" clearable />
          
        </el-form-item>
        <el-form-item label="">
          <el-select
            v-model="queryForm.tag"
            placeholder="分类筛选"
            style="width: 140px"
            clearable
          >
            <el-option
              v-for="item in typeList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
  
      <el-table v-loading="loading" :data="list">
        <!-- <el-table-column label="序号" type="index" width="100" /> -->
        <el-table-column align="center" label="" width="100">
          <template #default="scope">
            <el-avatar shape="square" size="medium" :src="scope.row.mainPic"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="title" label="标题">
          <template #default="scope">
            <strong>{{ scope.row.title }}</strong>
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="name" label="时长" width="100">
          <template #default="scope">
            <span>{{ scope.row.duration }}小时</span>
          </template>
        </el-table-column> -->
        <!-- <el-table-column align="center" prop="description" label="内容" show-overflow-tooltip>
        </el-table-column> -->
        <el-table-column label="更新时间" align="center" prop="createTime" width="130">
          <template #default="scope">
              <div>{{timestampToDate(scope.row.updatedAt)}}</div>
          </template>
        </el-table-column>
        <el-table-column label="分类" align="center" prop="status" width="130">
          <template #default="scope">
            <el-tag type="success">{{ scope.row.tags }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="likes" label="点赞/收藏">
          <template #default="scope">
            <div>{{scope.row.likes}} / {{scope.row.favs}}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作">
          <template #default="scope">
            <div>
              <el-button link type="success" icon="Top" @click="setTop(scope.row.id)" v-if="scope.row.isHot==0">首页推荐</el-button>
              <el-button link type="warning" icon="Close" @click="cancelTop(scope.row.id)" v-if="scope.row.isHot==1">撤销推荐</el-button>
              <el-button link type="success" icon="Document" @click="showDetail(scope.row)">详情</el-button>
            </div>
            <div>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row.id)">修改</el-button>
              <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row.id, -1)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
  
      <el-pagination background layout="prev, pager, next" v-model:page-size="queryForm.pageSize" v-model:current-page="queryForm.pageNo" :total="total" @current-change="getList" />
  
      <!-- 添加或修改对话框 -->
      <el-dialog v-model="open" :title="title" width="800px" append-to-body>
        <el-form label-width="130px" :model="editForm" :rules="rules" ref="formRef">
          <el-form-item label="标题" prop="title">
            <el-input
              v-model="editForm.title"
              auto-complete="off"
              placeholder=''
            ></el-input>
          </el-form-item>
          <el-form-item label="内容分类" prop="tags">
            <el-radio-group v-model="editForm.tags">
              <el-radio-button label="历史与发展" value="历史与发展" />
              <el-radio-button label="艺术特色" value="艺术特色" />
              <el-radio-button label="经典剧目" value="经典剧目" />
              <el-radio-button label="传承与保护" value="传承与保护" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="内容正文" prop="description" id='quillEditorQiniu'>
            <el-input
              v-model="editForm.description"
              type="textarea"
              :rows="5"
              placeholder="请输入内容正文"
            ></el-input>
          </el-form-item>
          <el-form-item label="题图" prop="role">
            <el-upload 
              class="avatar-uploader showUploader"
              ref="businessLicense"
              action
              :auto-upload="false"
              :show-file-list="false"
              :on-remove="handleRemoveLogo"
              :on-change="uploadLogoFile"
            >
            <ul class="img-list">
              <li v-if="editForm.mainPic==''" class="addpic"><el-icon><Plus/></el-icon></li>
            </ul>
            </el-upload>
            <ul class="img-list" v-if="editForm.mainPic!=''">
              <li class="img-li">
                <img :src="editForm.mainPic" class="avatar aspect-fill" style="width: 250px;height: 180px;" />
                <i class="logo-remove el-icon-delete" @click="handleRemoveLogo"><el-icon><Delete /></el-icon></i>
              </li>
            </ul>
          </el-form-item>
          <el-form-item label="附加图片" prop="role">
          <el-upload 
            class="avatar-uploader showUploader"
            ref="businessLicense"
            action
            multiple
            :auto-upload="false"
            :show-file-list="false"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :on-change="uploadSectionFile"
            :limit="6"
          >
            <ul class="img-list">
              <li v-for="(pic,i) in pics" :key="i" class="img-li" onclick="(function(e){e.stopPropagation()}(event))">
                <img :src="pic" class="avatar aspect-fill" style="width: 250px;height: 180px;"/>
                <i class="logo-remove el-icon-delete" @click="handleRemovePics(i)" ><el-icon><Delete /></el-icon></i>
              </li>
              <li v-if="pics.length==0 || pics.length<6" class="addpic avatar-uploader-icon"><el-icon><Plus /></el-icon></li>
            </ul>
          </el-upload>
        </el-form-item>
          <el-form-item label="视频链接" prop="videoUrl">
            <el-input
              v-model="editForm.videoUrl"
              auto-complete="off"
              placeholder="选填，如有视频请输入url"
            ></el-input>
          </el-form-item>
          
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="open = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>

      <!--详情对话框-->
    <el-dialog v-model="openDetail" :title="title" width="60%" append-to-body v-if="detailData">
      <!-- <el-descriptions class="margin-top" :column="2" border>
          <el-descriptions-item label="课程名称" labelStyle="width: 160px;">{{ detailData.ruleName }}</el-descriptions-item>
          <el-descriptions-item label="模板编号" labelStyle="width: 160px;">{{ detailData.ruleCode }}</el-descriptions-item>
          <el-descriptions-item label="版本号" labelStyle="width: 160px;">{{ detailData.version }}</el-descriptions-item>
          <el-descriptions-item label="创建时间" labelStyle="width: 160px;">{{ timestampToDayHM(detailData.createTime) }}</el-descriptions-item>
      </el-descriptions> -->
      <div class="introduction">{{ detailData.description }}</div>
    </el-dialog>
    </div>
  </template>
  <script setup lang="ts">
  import { ref, reactive, nextTick, toRef } from "vue";
  import baseService from "@/service/baseService";
  import { ElMessage, ElMessageBox } from "element-plus";
  import { timestampToDayHM, timestampToHM, timestampToDate, formatAmount } from "@/utils/utils"
  import { regionData, codeToText, TextToCode } from 'element-china-area-data'
  import { fileUploader } from '@/utils/upload.js'
  import { useRouter, useRoute } from 'vue-router';
  
  const router = useRouter();
  const route = useRoute();
  // 查询参数
  const queryForm = reactive({
    kw: '',
    tag: '',
    pageNo: 1,
    pageSize: 10
  });
  // 列表内容数量
  const total = ref(0);
  // 列表是否加载
  const loading = ref(true);
  // 列表返回值
  const list = ref<any[]>([]);
  const typeList = ref<any[]>(['历史与发展','艺术特色','经典剧目','传承与保护']);
  
  // 表单实例
  const formRef = ref();
  // 是否打开弹出框
  const open = ref(false);
  const isEdit = ref(0);
  const openDetail = ref(false);
  // 弹出框标题
  const title = ref('');
  const detailData = ref();
  // 提交表单数据
  let editForm = toRef(
    reactive({
      id: '',
      title: '',
      tags: '历史与发展',
      mainPic: '',
      pics: '',
      videoUrl: '',
      description: '',
      favs: 0,
      likes: 0,
    })
  );
  const options = ref(regionData)
  const selectedOptions = ref<any>([])
  //多图上传的返回图片url数组
  const pics = ref<any>([])
  const uploadUrlPath = ref();

  // 表单验证
  const rules = ref({
    title: [{ required: true, message: "请输入", trigger: "blur" }],
    description: [{ required: true, message: "请输入", trigger: "blur" }],
  });
  
  /**
   * 查询列表
   */
  const getList = () => {
    loading.value = true;
    baseService
      .post("/admin/display/list", queryForm).then((res) => {
        loading.value = false;
        if (res.code === 200) {
          list.value = res.data.records;
          total.value = res.data.totalrecord;
        } else {
          list.value = [];
        }
      })
      .catch(() => {
        loading.value = false;
      });
  };
  
  /**
   * 搜索按钮操作
   */
  function handleQuery() {
    queryForm.pageNo = 1;
    getList();
  }
  
  /**
   * 表单重置
   */
  function reset() {
    editForm.value = {
      id: '',
      title: '',
      tags: '历史与发展',
      mainPic: '',
      pics: '',
      videoUrl: '',
      description: '',
      favs: 0,
      likes: 0,
    };
    pics.value = []
  
    nextTick(() => {
      formRef.value?.resetFields();
    });
  }
  
  /**
   * 新增按钮操作
   */
  function handleAdd() {
    reset();
    open.value = true;
    isEdit.value = 0;
    console.log('图片:',pics.value)
    title.value = "添加";
  }

  //显示详情
  function showDetail(data: any){
    openDetail.value = true;
    title.value = "信息详情";
    detailData.value = data
  }
  
  /**
   * 修改按钮操作
   * @param id 主键
   */
  function handleUpdate(id: string) {
    open.value = true;
    title.value = "修改";
    isEdit.value = 1;
    reset();
    baseService.get(`/admin/display/info/${id}`).then((res) => {
      if (res.code === 200) {
        editForm.value = res.data;
        pics.value = res.data.pics.split(',')
      }
    });
  }

  function setTop(id: number){
    baseService.get(`/admin/display/top/${id}`).then((res) => {
      if (res.code === 200) {
        ElMessage.success('已推荐到首页');
        getList();
      }
    });
  }

  function cancelTop(id: number){
    baseService.get(`/admin/display/top/cancel/${id}`).then((res) => {
      if (res.code === 200) {
        ElMessage.warning('已从首页撤销');
        getList();
      }
    });
  }
  
  /**
   * 提交按钮
   */
  function submitForm() {
    formRef.value.validate((valid: boolean) => {
      if (!valid) return;
      // console.log('图片字段', pics.value)
      // editForm.value.mainPic = pics.value.join(',')
      editForm.value.pics = pics.value.join(',')
      baseService.post(`/admin/display/save`, editForm.value).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          open.value = false;
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }
  
  /**
   * 删除按钮操作
   * @param id 主键
   */
  function handleDelete(id: any, optType: number) {
    let msg = '确认要删除该内容吗？'
    ElMessageBox.confirm(msg, "提示").then(() => {
      baseService.get(`/admin/display/delete/${id}`).then((res) => {
        if (res.code === 200) {
          ElMessage.success(res.msg);
          getList();
        } else {
          ElMessage.error(res.msg);
        }
      });
    });
  }

  function handlePreview(file: any) {
      console.log(file);
  }
  function handleRemove(file: any, fileList: any) {
    alert('移除')
      //return this.$confirm(`确定移除 ${file.name}？`);
  }
  function beforeRemove(file: any, fileList: any) {
    alert('移除')
      // return this.$confirm(`确定移除 ${file.name}？`);
  }

  // 移除多图中的其中一张
  function handleRemovePics(idx: number){
    console.log('移除图片下标为：', idx)
    pics.value.splice(idx, 1);
  }

    // 图片上传
  function uploadSectionFile(file: any) {
    console.log('选定图片！',file)
    const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
    const isJPG = typeArr.indexOf(file.raw.type) !== -1;
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isJPG) {
      // ElMessage.error("只能是图片!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    if (!isLt3M) {
      // ElMessage.error("上传图片大小不能超过 3MB!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    // FormData 对象
    var formData = new FormData();
    // 文件对象
    formData.append("myFile", file.raw)
    console.log('上传图片表单：', formData)
    fileUploader(formData).then((res) => {
      if (res.data.errno==0) {
        //this.photoObj = res.data.data.objectId;
        console.log('图片上传成功！', res.data)
        pics.value.push(res.data.data);
      } else {
        // ElMessage.error(res.data.message);
      }
    })
  }

  // 上传LOGO图片
  function uploadLogoFile(file: any){
    const typeArr = ["image/png", "image/gif", "image/jpeg", "image/jpg"];
    const isJPG = typeArr.indexOf(file.raw.type) !== -1;
    const isLt3M = file.size / 1024 / 1024 < 3;
    if (!isJPG) {
      // ElMessage.error("只能是图片!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    if (!isLt3M) {
      // ElMessage.error("上传图片大小不能超过 3MB!");
      // this.$refs.upload.clearFiles();
      // this.files = null;
      return;
    }
    var formData = new FormData();
    formData.append("myFile", file.raw)
    fileUploader(formData).then((res) => {
      console.log('LOGO上传成功', res)
      if (res.data.errno==0) {
        editForm.value.mainPic=res.data.data[0]
      } else {
        // ElMessage.error(res.data.message);
      }
    })
  }
  // 移除LOGO图片
  function handleRemoveLogo(file: any){
    editForm.value.mainPic=''
    console.log('移除LOGO图片！',editForm.value.mainPic)
  }
  
  getList();
  </script>
  
<style scoped>
.price{
color: #F56C6C;
font-weight: bold;
}
.pointer{
    cursor: pointer;
}
.pointer:HOVER{
    color: #409eff;
}
.introduction{
  width: 80%;
  margin: 15px auto;
  white-space: pre-line;
}
.addpic{
  font-size: 22px;
  padding: 20px 25px 15px 25px;
  border: 2px dashed #ccc;
  color: #888;
  height: 68px;
}
.img-list{
  display: flex;
  flex-wrap: wrap;
}
.img-list .img-li{
  width: 260px;
  position: relative;
  margin-right: 10px;
}
.logo-remove{
  font-size: 22px;
  position: absolute;
  top: 10px;
  right: 10px;
  color: #f00;
  cursor: pointer;
  text-shadow: #000 4px 4px 5px;
}
.logo-remove .el-icon{
  box-shadow: #fff 3px 5px 6px;
  background-color: #fff;
}
.logo-remove:HOVER{
  color: #F56C6C;
}
</style>
  